package com.ruoyi.oa.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.wx.WxMaConfiguration;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.oa.domain.LeaveTeacher;
import com.ruoyi.oa.domain.ManageStudent;
import com.ruoyi.oa.service.IManageStudentService;
import com.ruoyi.oa.service.impl.ManageStudentServiceImpl;
import com.ruoyi.project.nczxwechat.stuinfo.domain.WxStuinfo;
import com.ruoyi.project.nczxwechat.stuinfo.service.IWxStuinfoService;
import com.ruoyi.project.nczxwechat.wechat.domain.WxUserInfo;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.List;

/**
 * 微信相关功能控制器
 */
@Controller
@RequestMapping("/wxapi")
public class WxApiController {

    @Autowired
    IManageStudentService studentService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 先查询学生信息是否存在
     * @param stuno 学生唯一ID
     */
    @GetMapping("/getUserInfo")
    @ResponseBody
    public AjaxResult getUserInfo(@NotEmpty(message = "获取学生信息错误") String stuno){
        ManageStudent student = this.studentService.getStudentByStuno(stuno, "1");
            if (student != null && StringUtils.isNotEmpty(student.getStuno())){
                return AjaxResult.success(student);
            }else {
                return AjaxResult.error("暂未查到绑定信息，请核对或与相关人员联系！");
            }
    }
    @PostMapping("/wxlogin_stu")
    @ResponseBody
    public AjaxResult wxlogin(@NotEmpty(message = "授权信息错误") @RequestBody WxUserInfo wxUserInfo)  {
        ManageStudent wxStuinfos = studentService.getStudentByStuno(wxUserInfo.getStuno(), "1");//通过学生唯一ID查询学生基本信息
        //通过微信端api获取当前用户的openid
        WxMaJscode2SessionResult session = null;
        try {
            session = WxMaConfiguration.wxMaService.getUserService().getSessionInfo(wxUserInfo.getCode());
            //通过当前用户的唯一编号与opendi查询学生信息
            ManageStudent reswxStuinfo = studentService.selectStudentByStunNoAndOpenID(wxUserInfo.getStuno(), wxStuinfos.getOpenId());
            //判断是否已绑定：就是旧的openid是否存在
            if (StringUtils.isEmpty(wxStuinfos.getOpenId())){
                //没有绑定就开始绑定，并返回相关数据
                updateUserInfo(session.getOpenid(),wxUserInfo, wxStuinfos);
                return AjaxResult.success(wxStuinfos);
                //存在并且已经绑定了判断是否跟原来绑定的一致
            }else if (StringUtils.isNotEmpty(reswxStuinfo.getOpenId()) && session.getOpenid().equals(reswxStuinfo.getOpenId())){
                //数据一致就返回库里的数据，成功登录并返回相关数据
                return AjaxResult.success(wxStuinfos);
            }else {
                //不一致就反馈错误信息
                return AjaxResult.error("你已经绑定过其他微信账号，请勿重复绑定！!");
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return AjaxResult.error("本次授权失败，请与管理员联系");
        }
    }
    public String updateUserInfo(String openID, WxUserInfo wxuserinfo, ManageStudent wxStuinfos){
        Date date=new Date();
        wxStuinfos.setAvatarUrl(wxuserinfo.getAvatarUrl());
        wxStuinfos.setOpenId(openID);
        wxStuinfos.setNickName(wxuserinfo.getNickName());
        wxStuinfos.setFirstLoginTime(date);
        studentService.updateManageStudent(wxStuinfos);
        return "绑定成功";
    }
    /**
     * 小程序教师用户登录
     * @return
     */
    @PostMapping("/wxlogin_teacher")
    @ResponseBody
    public AjaxResult wxloginTeacher(@NotEmpty(message = "授权信息错误") @RequestBody JSONObject jo)  {

        String username = (String)jo.get("username");
        String password = (String)jo.get("password");

        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return AjaxResult.error("用戶名或密码不能位空！!");
        }
        SysUser user = userService.selectUserByLoginName(username);

        if(null == user) {
            return AjaxResult.error("用戶不存在！!");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            return AjaxResult.error("用戶状态异常，请联系管理员！!");
        }

        if (passwordService.matches(user, password)) {
            return AjaxResult.success(user);
        } else {
            return AjaxResult.error("密码错误，请重新输入密码！!");
        }

    }

    /**
     * 获取字典列表
     */
    @GetMapping("/listDictData")
    @ResponseBody
    public AjaxResult listDictData(String dictType)
    {
        SysDictData dictData = new SysDictData();
        dictData.setDictType(dictType);
        dictData.setStatus("0");//状态是正常的
        List<SysDictData> list = sysDictDataService.selectDictDataList(dictData);
        return AjaxResult.success(list);
    }

    /*@ApiOperation(value = "获取微信openId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "微信code", required = true, dataType = "string"),
    })
    @PostMapping("/wxlogin_stu")
    @ResponseBody
    public AjaxResult wxlogin(@NotEmpty(message = "授权信息错误") @RequestBody WxUserInfo wxUserInfo)  {
        WxStuinfo wxStuinfos = stuinfoService.selectWxStuinfoByStuNo(wxUserInfo.getStuno());//通过学生唯一ID查询学生基本信息
        //通过微信端api获取当前用户的openid
        WxMaJscode2SessionResult session = null;
        try {
            session = WxMaConfiguration.wxMaService.getUserService().getSessionInfo(wxUserInfo.getCode());
            //通过当前用户的唯一编号与opendi查询学生信息
            WxStuinfo reswxStuinfo = stuinfoService.selectWxStuinfoByStuNoAndOpenID(wxUserInfo.getStuno(), wxStuinfos.getOpenId());
            //判断是否已绑定：就是旧的openid是否存在
            if (StringUtils.isEmpty(wxStuinfos.getOpenId())){
                //没有绑定就开始绑定，并返回相关数据
                updateUserInfo(session.getOpenid(),wxUserInfo);
                return AjaxResult.success(wxStuinfos);
                //存在并且已经绑定了判断是否跟原来绑定的一致
            }else if (StringUtils.isNotEmpty(reswxStuinfo.getOpenId()) && session.getOpenid().equals(reswxStuinfo.getOpenId())){
                //数据一致就返回库里的数据，成功登录并返回相关数据
                return AjaxResult.success(wxStuinfos);
            }else {
                //不一致就反馈错误信息
                return AjaxResult.error("你已经绑定过其他微信账号，请勿重复绑定！!");
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return AjaxResult.error("本次授权失败，请与管理员联系");
        }
    }
    public String updateUserInfo(String openID, WxUserInfo wxuserinfo){
        Date date=new Date();
        WxStuinfo wxStuinfos = stuinfoService.selectWxStuinfoByStuNo(wxuserinfo.getStuno());
        wxStuinfos.setAvatarUrl(wxuserinfo.getAvatarUrl());
        wxStuinfos.setOpenId(openID);
        wxStuinfos.setNickName(wxuserinfo.getNickName());
        wxStuinfos.setFirstLoginTime(date);
        stuinfoService.updateWxStuinfo(wxStuinfos);
        return "绑定成功";
    }*/

}
